﻿using System;
using System.ServiceModel;
using System.Web;
using DxMvcApplication.SecurityServiceReference;

namespace DxMvcApplication.Repositories.Core.Security
{
    /// <summary>
    /// Base class for all Repositories. 
    /// Provides common repository functionality, including:
    ///   - Management of Service client.
    ///   - Offers common request-response correlation check.
    /// </summary>
    public abstract class SecurityRepositoryBase
    {

        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        protected ActionSecurityServiceClient SecurityServiceClient
        {
            get
            {                
                // Check if not initialized yet
                if (HttpContext.Current.Session["SecurityServiceClient"] == null)
                    HttpContext.Current.Session["SecurityServiceClient"] = new ActionSecurityServiceClient();
                
                // If current client is 'faulted' (due to some error), create a new instance.
                var client = HttpContext.Current.Session["SecurityServiceClient"] as ActionSecurityServiceClient;                                
                if (client != null && client.State == CommunicationState.Faulted)
                {
                    try { client.Abort(); }
                    catch { /* no action */ }

                    client = new ActionSecurityServiceClient();
                    HttpContext.Current.Session["SecurityServiceClient"] = client;
                }
                return client;
            }
        }

        /// <summary>
        /// Correlates requestid with returned response correlationId. 
        /// These must always match. If not, request and responses are not related.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected void Correlate(RequestBase request, ResponseBase response)
        {
            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("RequestId and CorrelationId do not match.");
        }
    }
}